<?php
declare(strict_types=1);
namespace App\ZxAdmin\Content\Album;
use App\Controller;
use OSS\Core\OssException;
use OSS\OssClient;


// hook controller_zx_admin_content_album_sys_oss_use.php

/**
 * @title   Oss附件管理
 * @auth    true
 * @login   true
 * @menu    true
 * @component   vlist/index.vue
 * @icon    el-icon-menu
 * @active  true
 * @affix   false
 * @rank    99
 */
class SysOss extends Controller
{
    // hook controller_zx_admin_content_album_sys_oss_public_start.php

    // make public SysAlbumAttach ZxAdmin\Content\Album
    /*
    protected array $echo_field 	=	[];
    protected array $edit_field	    =	[];
    protected array $add_field      =	[];
    protected array $field_fields_kv	=	[];
    protected array $Columns	    =	[];
    */

    public const make=1;
    /**
     * @title   列表配置
     */
    public const Conf=[
        'pageSize'=>100,
        'remoteSort'=>0,
        'remoteFilter'=>0,
        'remoteSummary'=>0,
        'hidePagination'=>1,
        'hideRefresh'=>0,
        'hideSetting'=>0,
        'hideDo'=>0,
        'add'=>0,
        'start'=>0,
        'stop'=>0,
        'delete'=>1,
        'import'=>0,
        'export'=>0
    ];
    /**
     * @title   列操作
     */
    public const Tools=[];
   /**
    * @title   列配置
    */
    public const Columns=[];
    /**
     * @title   筛选
     */
    public const Filter=[];
    /**
     * @title   添加内容
     */
    public const AddForm=[];
    /**
     * @title   编辑内容
     */
    public const EditForm=[];

    // hook controller_zx_admin_content_album_sys_oss_public_end.php
    /**
     * @title  下发配置
     * @rank    99
     */
    public function action_Conf()
    {
        // hook controller_zx_admin_content_album_sys_oss_conf_start.php
        $data=[];
        $Columns=[[
            'label'=> "文件名",
            'prop'=> "Name",
            'width'=> "600"
        ],
        [
            'label'=> "大小",
            'prop'=> "Size",
            'width'=> "200"
        ],
        [
            'label'=> "文件类型",
            'prop'=> "Type",
            'width'=> "150"
        ],
        [
            'label'=> "ETag",
            'prop'=> "ETag",
            'width'=> "300"
        ],
        [
            'label'=> "更新时间",
            'prop'=> "LastModified",
            'width'=> "200"
        ]];

        foreach (self::Columns as $row){
            $Columns[]=$row;
        }
        /*

        $data['Column']=$this->Columns;
        $data['Tools'] = [];
        $Tools = [];
        foreach ($Tools as $k=> $row){
            switch ($row['do']){
                case 'add':
                case 'edit':
                case 'delete':
                case 'into':
                case 'start':
                case 'stop':
                    if($this->SysRoleAuth->Check($this->token->RoleID)){
                        $data['Tools'][]=$row;
                    }
                    break;
            }
        }
        */

        $bucketListInfo = $this->ossClient->listBuckets();
        $bucketList = $bucketListInfo->getBucketList();

        $tabs=[];
        foreach ($bucketList as $k=>$v){

            $tabs[]=[
                'Location'=>$v->getLocation(),
                'Name'=>$v->getName(),
                'Index'=>$v->getName(),
                'CreateDate'=>$v->getCreateDate()
            ];
        }
        // make conf SysAlbumAttach ZxAdmin\Content\Album
        // hook controller_zx_admin_content_album_sys_oss_conf_end.php
        $this->response('0000', ['Tabs' =>$tabs,'Conf' =>self::Conf,'Filter'=>self::Filter,'Tools'=>self::Tools,'Columns'=>$Columns,'data' =>$data]);
    }

    public function GetList($tab,$dir,$marker)
    {
        //'delimiter'=>'',
        $options =['prefix' => $dir,'marker' => $marker,'max-keys' => 1000];
        $listObjectInfo = $this->ossClient->listObjects($tab,$options);
        $marker=$listObjectInfo->getNextMarker();
        $objectList = $listObjectInfo->getObjectList();
        $prefixList = $listObjectInfo->getPrefixList();
        $data=[];
        if (!empty($prefixList)) {
            foreach ($prefixList as $prefixInfo) {
                $data[]=[
                    'Name'=>$prefixInfo->getPrefix(),
                    'Bucket'=>$tab,
                    'Size'=>'',
                    'Type'=>'Dir',
                    'ETag'=>'',
                    'LastModified'=>'',
                ];
            }
        }
        if (!empty($objectList)) {
            foreach ($objectList as $objectInfo) {
                $data[]=[
                    'Name'=>$objectInfo->getKey(),
                    'Bucket'=>$tab,
                    'Size'=>formatSize($objectInfo->getSize()),
                    'Type'=>$objectInfo->getType(),
                    'ETag'=>trim($objectInfo->getETag(),'"'),
                    'LastModified'=>$objectInfo->getLastModified(),
                ];
            }
        }
        return ['data'=>$data,'marker'=>$marker];
    }
    /**
     * @title   下发列表数据
     * @rank    99
     */
    public function action_Index()
    {
        // hook controller_zx_admin_content_album_sys_oss_index_start.php
        $tab=$this->request->param('tab', '');
        $dir=$this->request->param('dir', '');
        $op =['prefix'=> $dir];
        $stat = $this->ossClient->getBucketStat($tab,$op);
        $data['total']=$stat->getObjectCount();
        $data['stat']=[
            'storage'=>$stat->getStorage(),// 获取Bucket的总存储量，单位为字节。
            'count'=>$stat->getObjectCount(),// 获取Bucket中总的Object数量。
            /*
        // 获取Bucket中Live Channel的数量。
                printf("Bucket ".$bucket." live channel count is:".$stat->getLiveChannelCount().PHP_EOL);
        // 此次调用获取到的存储信息的时间点，格式为时间戳，单位为秒。
                printf("Bucket ".$bucket." last modified time is:".$stat->getLastModifiedTime().PHP_EOL);
        // 获取标准存储类型Object的存储量，单位为字节。
                printf("Bucket ".$bucket." standard storage is:".$stat->getStandardStorage().PHP_EOL);
        // 获取标准存储类型的Object的数量。
                printf("Bucket ".$bucket." standard object count is:".$stat->getStandardObjectCount().PHP_EOL);
        // 获取低频访问类型Object的计费存储量，单位为字节。
                printf("Bucket ".$bucket." infrequent access storage is:".$stat->getInfrequentAccessStorage().PHP_EOL);
        // 获取低频访问类型Object的实际存储量，单位为字节。
                printf("Bucket ".$bucket." infrequent access real storage is:".$stat->getInfrequentAccessRealStorage().PHP_EOL);
        // 获取低频访问类型的Object数量。
                printf("Bucket ".$bucket." infrequent access object count is:".$stat->getInfrequentAccessObjectCount().PHP_EOL);
        // 获取归档存储类型Object的计费存储量，单位为字节。
                printf("Bucket ".$bucket." archive storage is:".$stat->getArchiveStorage().PHP_EOL);
        // 获取归档存储类型Object的实际存储量，单位为字节。
                printf("Bucket ".$bucket." archive real storage is:".$stat->getArchiveRealStorage().PHP_EOL);
        // 获取归档存储类型的Object数量。
                printf("Bucket ".$bucket." archive object count is:".$stat->getArchiveObjectCount().PHP_EOL);
        // 获取冷归档存储类型Object的计费存储量，单位为字节。
                printf("Bucket ".$bucket." cold archive storage is:".$stat->getColdArchiveStorage().PHP_EOL);
        // 获取冷归档存储类型Object的实际存储量，单位为字节。
                printf("Bucket ".$bucket." cold archive real storage is:".$stat->getColdArchiveRealStorage().PHP_EOL);
        // 获取冷归档存储类型的Object数量。
                printf("Bucket ".$bucket." cold archive object count is:".$stat->getColdArchiveObjectCount().PHP_EOL);
        */
        ];
        $data['data']=[];
        $marker='';
        $count=1000;
        if(!empty($dir)){
            $last_slash_position = strrpos($dir, "/");
            if ($last_slash_position !== false) {
                $result = substr($dir, 0, $last_slash_position);
            } else {
                $result = $dir;
            }
            $data['data'][]=['Name'=>$result,'Size'=>'','Type'=>'Dir','ETag'=>'','LastModified'=>'',];
        }
        while ($count>=1000){
            $dataTmp=$this->GetList($tab,$dir,$marker);
            $marker=$dataTmp['marker'];
            if(!empty($dataTmp['data'])){
                $data['data']+=$dataTmp['data'];
                $count=count($dataTmp['data']);
            }
        }
        // hook controller_zx_admin_content_album_sys_oss_index_end.php
        $this->response('0000', $data);
    }

    //need_delete_start
     /**
      * @title   删除数据
      */
    public function action_Index_Delete()
    {
        // hook controller_zx_admin_content_album_sys_oss_delete_start.php
        $data = $this->request->param('data',[]);
        $this->CheckEmpty([$data], ['操作数据为空']);
        foreach ($data as $row){
            $bucket=$row['Bucket'];
            $object=$row['Name'];
            $this->ossClient->deleteObject($bucket, $object);
        }

        // hook controller_zx_admin_content_album_sys_oss_delete_end.php
        $this->response('0000', ['data' =>count($data)]);
    }
    //need_delete_end
    /**
     * @title   上传文件
     */
    public function action_Upload()
    {
        $dir=$this->request->param('dir', '');
        try {
            $options = array(
                OssClient::OSS_HEADERS => array(
                    'x-oss-object-acl' => 'private',
                    'x-oss-meta-info' => 'yourinfo'
                ),
            );
            $filepath =$this->request->getFiles()['file']['tmp_name'];
            //$filename
            $this->ossClient->uploadFile($dir, $filename, $filepath);
        } catch (OssException $e) {
            print $e->getMessage();
        }

    }

    // hook controller_zx_admin_content_album_sys_oss_end.php
}
?>